package com.dueeeke.dkplayer.util;

import android.util.Log;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpTool {
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    static OkHttpClient client = new OkHttpClient().newBuilder().callTimeout(10, TimeUnit.SECONDS).build();

    public static JSONObject post (String url, HashMap<String,String> postData) throws IOException {
        return request(url, "POST", postData);
    }

    public static JSONObject get (String url, Map<String,String> postData) throws IOException {
        return request(url, "GET", postData);
    }

    static JSONObject request(String url, String method, Map<String,String> postData) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        Request request;
        if (method.equals("GET")) {
            if (!postData.isEmpty()) {
                url += "?";
                for (Map.Entry<String, String> entry : postData.entrySet()) url += entry.getKey() + "=" + entry.getValue() + "&";
            }
            request = new Request.Builder().url(url).build();
        } else {
            if (!postData.isEmpty()) {
                for (Map.Entry<String, String> entry : postData.entrySet()) builder.add(entry.getKey(), entry.getValue());
            }
            request = new Request.Builder().url(url).post(builder.build()).build();
        }
        Log.d("REQUEST", request.toString());
        Response response = client.newCall(request).execute();
        Log.d("REQUEST", response.toString());
        try {
            return new JSONObject(response.body().string());
        } catch (JSONException e) {
            throw new IOException("请求数据错误:" + response.body().string());
        }
    }
}
